using System.Threading.Tasks;
using CoreApp.DBAccess;
using CoreApp.DBModel;
using Dapper;
using MySql.Data.MySqlClient;
using Microsoft.Extensions.Options;
using System.Data;

namespace CoreApp.DapperAccess
{
    public class RepositoryBase<T> : IRepositoryBase<T>
    {
        public string dbConnStr;
        public IDbConnection conn;

        public RepositoryBase(IOptions<DBConnectionConfig> option)
        {
            dbConnStr = option.Value.MySqlConnectionString;
            conn = new MySqlConnection(dbConnStr);         
            conn.Open();   
        }

        public async Task<int> Insert(T entity, string sql)
        {
            int result=0;
            using (conn)
            {
                result = await conn.ExecuteAsync(sql, entity);
            }
            return result;
        }        

        public async Task<int> Delete(int Id, string sql)
        {
            int result=0;
            using (conn)
            {
                 result = await conn.ExecuteAsync(sql, new { Id = Id });
            }
            return result;
        }

        public async Task<int> Update(T entity, string sql)
        {
            int result=0;
            using (conn)
            {
                 result = await conn.ExecuteAsync(sql, entity);
            }
            return result;
        }

        public async Task<T> Query(int Id, string sql)
        {
            using (conn)
            {
                return await conn.QueryFirstOrDefaultAsync<T>(sql, new { Id = Id });
            }
        }
    }
}